const express = require('express')
const router = express.Router()
const rds = require('../tmall-db/rds')
const logger = require('../logger')

// 产品列表页面
router.get('/', async (req, res) => {
    try {
        const [products] = await rds.query(`
            SELECT * FROM mta_products
            ORDER BY sort_order ASC, id DESC
        `)

        res.render('admin/products/index', {
            title: '解决方案产品管理',
            products: products.map(product => ({
                ...product,
                tags: JSON.parse(product.tags || '[]'),
                refs: JSON.parse(product.refs || '[]')
            }))
        })
    } catch (err) {
        logger.error('获取产品列表失败:', err)
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取产品列表失败',
            description: err.message,
            icon: 'weui-icon-warn weui-icon_msg'
        })
    }
})

// 新建产品页面
router.get('/new', (req, res) => {
    res.render('admin/products/edit', {
        title: '新建解决方案产品',
        product: {
            id: '',
            name: '',
            evidence_level: '',
            category: '',
            tags: [],
            image: '',
            title: '',
            spec: '',
            summary: '',
            refs: [],
            detail: '',
            path: '',
            view_count: 0,
            like_count: 0,
            bookmark_count: 0,
            comment_count: 0,
            sort_order: 100
        },
        isNew: true
    })
})

// 编辑产品页面
router.get('/edit/:id', async (req, res) => {
    try {
        const [[product]] = await rds.query('SELECT * FROM mta_products WHERE id = ?', [req.params.id])

        if (!product) {
            return res.status(404).render('warn', {
                title: '未找到',
                message: '产品不存在',
                description: '请检查产品ID是否正确',
                icon: 'weui-icon-warn weui-icon_msg'
            })
        }

        res.render('admin/products/edit', {
            title: '编辑解决方案产品',
            product: {
                ...product,
                tags: JSON.parse(product.tags || '[]'),
                refs: JSON.parse(product.refs || '[]')
            },
            isNew: false
        })
    } catch (err) {
        logger.error('获取产品详情失败:', err)
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取产品详情失败',
            description: err.message,
            icon: 'weui-icon-warn weui-icon_msg'
        })
    }
})

// 保存产品（新建或更新）
router.post('/save', async (req, res) => {
    try {
        const {
            id, name, evidence_level, category, tags, image, title, spec, summary,
            refs, detail, path, view_count, like_count, bookmark_count, comment_count, sort_order
        } = req.body

        // 处理标签和引用，确保它们是数组格式
        const tagsArray = Array.isArray(tags) ? tags : (typeof tags === 'string' ? tags.split(',').map(t => t.trim()).filter(t => t) : [])
        let refsArray = []

        if (refs && typeof refs === 'string') {
            try {
                refsArray = JSON.parse(refs)
            } catch (e) {
                refsArray = []
            }
        } else if (Array.isArray(refs)) {
            refsArray = refs
        }

        // 准备数据
        const productData = {
            name,
            evidence_level,
            category,
            tags: JSON.stringify(tagsArray),
            image,
            title,
            spec,
            summary,
            refs: JSON.stringify(refsArray),
            detail,
            path,
            view_count: parseInt(view_count) || 0,
            like_count: parseInt(like_count) || 0,
            bookmark_count: parseInt(bookmark_count) || 0,
            comment_count: parseInt(comment_count) || 0,
            sort_order: parseInt(sort_order) || 100,
            updated_at: new Date()
        }

        let result
        if (id) {
            // 更新现有产品
            const updateFields = Object.entries(productData).map(([key]) => `${key} = ?`).join(', ');
            const updateValues = Object.values(productData);
            updateValues.push(id);

            [result] = await rds.query(`UPDATE mta_products SET ${updateFields} WHERE id = ?`, updateValues);
            logger.info(`用户 ${req.session.totemUID} 更新了产品 ${id}`);
        } else {
            // 创建新产品
            productData.created_at = new Date();
            const fields = Object.keys(productData).join(', ');
            const placeholders = Object.keys(productData).map(() => '?').join(', ');
            const values = Object.values(productData);

            [result] = await rds.query(
                `INSERT INTO mta_products (${fields}) VALUES (${placeholders})`,
                values
            );
            logger.info(`用户 ${req.session.totemUID} 创建了新产品 ${result.insertId}`);
        }

        res.redirect('/apps/admin/products')
    } catch (err) {
        logger.error('保存产品失败:', err)
        res.status(500).render('warn', {
            title: '系统错误',
            message: '保存产品失败',
            description: err.message,
            icon: 'weui-icon-warn weui-icon_msg'
        })
    }
})

// 删除产品
router.post('/delete/:id', async (req, res) => {
    try {
        const [result] = await rds.query('DELETE FROM mta_products WHERE id = ?', [req.params.id])

        if (result.affectedRows === 0) {
            return res.status(404).json({ success: false, message: '产品不存在' })
        }

        logger.info(`用户 ${req.session.totemUID} 删除了产品 ${req.params.id}`)
        res.json({ success: true })
    } catch (err) {
        logger.error('删除产品失败:', err)
        res.status(500).json({ success: false, message: err.message })
    }
})

module.exports = router
